<?php
namespace App\Admin\Controllers;
use App\Admin\Models\Levels;
use App\Admin\Models\Member;
use App\Admin\Models\OrderCommissions;
use App\Admin\Models\Orders;
use App\Admin\Models\User;
use App\Admin\Models\UserMonthIncome;
use App\Admin\Models\Wallets;
use App\Admin\Models\Withdraw;
use App\Admin\Models\WwwExtend;
use Common\Common;
use Common\CommonAd;
use Common\ControllerAdBase;
use Common\Models\Operator;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;

class MemberController extends ControllerAdBase
{

    public function initialize()
    {
        parent::initialize();
    }


    /**
     * 会员列表
     */
    public function listAction()
    {
        $member                     = new Member();
        $this->params['limit']      = isset($this->params['limit']) ? $this->params['limit'] : 10;
        $this->params['page']       = isset($this->params['page']) ? $this->params['page'] : 1;
        $this->params['keywords']   = isset($this->params['keywords']) ? $this->params['keywords'] : '';
        $this->params['is_appuser'] = isset($this->params['is_appuser']) ? $this->params['is_appuser'] : '';
        $this->params['order']      = isset($this->params['order']) ? $this->params['order'] : '';
        $this->params['sort']       = isset($this->params['sort']) ? $this->params['sort'] : 'desc';
        $list          = $member->member_list_two($this->params, $this->params['limit'], $this->params['page']);
        $list['total'] = (int)$list['total'];
        $member        = new Member();
        $LevelsDb = new Levels();
        foreach ($list['items'] as $key => &$value) {
            $level = $LevelsDb->findFirstById($value['level_id']);
            $value['level_name'] = $level ? $level->name : '';
            $referer_info = $member->findFirstById($value['referer_id']);
            $value['referer_phone'] = $referer_info ? $referer_info->phone : '';
            $value['referer_name']  = $referer_info ? $referer_info->nickname : '';
            $value['referer_id']    = $referer_info ? $referer_info->id : 0;
            $value['estimate_money'] = "0.00";

            if (!$value['commissions']) {
                $value['commissions'] = 0;
            }
            $path         = $value['path'] . ',' . $value['referer_id'];
            $xiaji = $member->subordinate_count($value['id']);
            $order                = new OrderCommissions();
            $params['user_id']    = $value['id'];
            $value['order_count'] = $order->get_selfmy_order_commition($params, 1);;
            $teamNum           = $member->team_num($value['id'], $value['referer_id'], $value['path']);
            $value['direct']   = $teamNum['direct'];
            $value['indirect'] = $teamNum['indirect'];
            $value['team']     = $teamNum['team'];
            $value['count']    = $teamNum['count'];
            $value['is_modify_superior'] = true;
            if ($xiaji > 0 || $value['order_count'] > 0) {
                $value['is_modify_superior'] = false;
            }
            $value['path_phone'] = $member->get_referer_list($path);
            $value['withdraws']  = CommonAd::number_randtwo($value['withdraws'] + $value['amount']);
        }
        $this->ok($list);
    }

    /**
     * 获取等级
     */
    public function level_listAction(){
        $FLevelDb = new Levels();
        $get_list = $FLevelDb->find()->toarray();
        $this->ok($get_list);
    }

    public function get_phoneAction()
    {
        if (!isset($this->params['phone']) || empty($this->params['phone'])) {
            $this->fail(-1, '缺少phone');
        }
        $member = new Member();
        $info   = $member->findFirstByPhone($this->params['phone']);
        if (!$info) {
            $this->fail(-1, '上级不存在!');
        }
        $this->ok($info->nickname);
    }

    /**
     * 关系链
     */
    public function relation_chainAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '缺少user_id');
        }
        $member = new Member();
        $info   = $member->find_by_id($this->params['user_id']);
        $ids    = $info['path'] ? $info['path'] . ',' . $info['referer_id'] . ',' . $info['id'] : $info['referer_id'] . ',' . $info['id'];
        $sql    = "select id,nickname,level_id from f_users where id in ($ids) order by FIELD(id,$ids)";
        $list = $this->getDI()->get('dbMaster')->fetchAll($sql);
        if (!empty($list)) {
            $level              = new Levels();
            foreach ($list as $key => $val) {
                $list[$key]['level_name'] = $level->find_by_level_name($val['level_id']);
                $list[$key]['level_commission'] = 0;
            }
        }
        $this->ok($list);
    }

    /**
     * 调整上级
     */
    public function update_superiorAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '缺少user_id');
        }
        if (!isset($this->params['phone']) || empty($this->params['phone'])) {
            $this->fail(-1, '缺少phone');
        }
        $member = new Member();
        $ref    = $member->findFirstByPhone($this->params['phone']);
        if (!$ref) {
            $this->fail(-1, '上级不存在!');
        }
        $order       = new Orders();
        $order_count = $order->order_count($this->params['user_id']);
        $xiaji       = $member->subordinate_count($this->params['user_id']);

        if ($order_count > 0 || $xiaji > 0) {
            $this->fail(-1, '已有下级或者已经下单不能修改!');
        }

        $invitecodeDb         = new InviteCodes();
        $code                 = $invitecodeDb->usedInviteCode();
        $userInfo             = $member->findFirstById($this->params['user_id']);
        $userInfo->referer_id = $ref->id;
        $userInfo->path       = $ref->path ? $ref->path . ',' . $ref->referer_id : $ref->referer_id;
        if (empty($userInfo->invite_code)) {
            $userInfo->invite_code = $code;
        }
        if ($userInfo->save()) {
            $this->ok('调整成功!');
        }
        $this->fail(-1, '调整失败!');
    }

    /**
     * 会员订单
     */
    public function orderlistAction()
    {//当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 100;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $orderCommission = new OrderCommissions();
        $list            = $orderCommission->orderuserlist($this->params);
        $paginator       = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list            = $paginator->getPaginate();
        $this->ok($list);
    }

    /**
     * 修改用户等级
     */
    public function updatelevelAction()
    {
        if (!isset($this->params['id']) && empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }

        if (!isset($this->params['is_forever'])) {
            $this->fail(-1, 'is_forever不能为空');
        }
        if ($this->params['is_forever'] == 1) {
            if (!isset($this->params['num']) && empty($this->params['num'])) {
                $this->fail(-1, 'num不能为空');
            }
        }
        $member = new Member();
        $info   = $member->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该用户不存在');
        }
        if (empty($info['invite_code'])) {
            $this->fail(-1, '该用户未填写邀请码!');
        }
        $level_arr = [1, 2, 3, 4];
        if (empty($this->params)) {
            $this->fail(-1, '请输入等级');
        } else {
            if (!in_array($this->params['level_id'], $level_arr)) {
                $this->fail(-1, '该等级不存在，请重新输入');
            }
        }
        $info['level_id'] = $this->params['level_id'];
        $result           = $member->save_member($info);
        if ($result) {
            $wwExten            = new WwwExtend();
            $wwExten            = $wwExten->find_by_user_id($this->params['id']);
            $wwExten->level_id  = $this->params['level_id'];
            $wwExten->date_time = date('Y-m-d H:i:s');
            switch ($this->params['level_id']) {
                case 2:
                    if ($this->params['is_forever'] == 0) {
                        $wwExten->svip_count_time = $this->params['num'];
                        $wwExten->svip_forever    = 0;
                    } else {
                        $wwExten->svip_forever = 1;
                    }
                    break;
                case 3:
                    if ($this->params['is_forever'] == 0) {
                        $wwExten->hhr_count_time = $this->params['num'];
                        $wwExten->hhr_forever    = 0;
                    } else {
                        $wwExten->hhr_forever = 1;
                    }
                    break;
                case 4:
                    if ($this->params['is_forever'] == 0) {
                        $wwExten->gjhhr_count_time = $this->params['num'];
                        $wwExten->gjhhr_forever    = 0;
                    } else {
                        $wwExten->gjhhr_forever = 1;
                    }
                    break;
            }
            $wwExten->save();
            $this->ok([]);
        } else {
            $this->fail(-1, '等级更改失败');
        }
    }

    /**
     * 启用禁用
     */
    public function isdisableAction()
    {
        if (!isset($this->params['id']) && empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $member = new Member();
        $info   = $member->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该用户不存在');
        }
        if ($info['is_disable']) {
            ToolsController::invite_add_one($info['referer_id'], $info['path']);
            $info['is_disable'] = 0;
        } else {
            ToolsController::invite_subtraction_one($info['referer_id'], $info['path']);
            $info['is_disable'] = 1;
        }
        $member1 = new Member();
        $result  = $member1->save_member($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }
    }

    //根据用户id查找手机号
    public function memberinfoAction()
    {
        $member = new Member();
        $info   = $member->find_by_id($this->params['id']);
        if ($info) {
            $levelDb            = new Levels();
            $info['level_name'] = $levelDb->find_by_level_name($info['level_id']);
            $member_user        = $member->find_by_id($info['referer_id']);
            if ($member_user) {
                $nickname = $member_user['nickname'] ? $member_user['nickname'] : $member_user['phone'];
            } else {
                $nickname = '';
            }
            $info['referer_name'] = $nickname;
            $walletDb             = new Wallets();
            $wallet               = $walletDb->findbyUserId($info['id']);
            $info['amount']       = $wallet ? $wallet->amount : '0.00';
            $user_incomeDb        = new UserMonthIncome();
            $info['all_amount']   = Common::number_randtwo($user_incomeDb->get_all_income($info['id']));
            $withdrawDb           = new Withdraw();
            $info['withdraw']     = Common::number_randtwo($withdrawDb->user_money_have_in_hand($info['id']));
            $commistion           = new OrderCommissions();
            $info['commsition']   = Common::number_randtwo($commistion->get_my_self_sum($info['id']));
            $info['savegoods']    = Common::number_randtwo($commistion->get_my_all_sum($info['id']));

            $this->ok($info);
        } else {
            $this->fail(-1, '数据不存在或以删除');
        }
    }


    /**
     * 自购订单和粉丝订单
     */
    public function selffanorderAction()
    {
        $data   = [];
        $params = $this->params;
        if (!empty($params['commission_type'])) {
            $data['commission_type'] = $params['commission_type'];
        } else {
            $data['commission_type'] = 1;
        }
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        if (isset($params['order_status']) && !empty($params['order_status'])) {
            $data['order_status'] = $params['order_status'];
        }
        if (isset($params['tk_create_time']) && !empty($params['tk_create_time'])) {
            $data['tk_create_time'] = $params['tk_create_time'];
        }
        $model           = new Orders();
        $data['user_id'] = $params['user_id'];
        $list            = $model->getOrderList($data);
        $paginator       = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items      = $paginator->getPaginate();
        if ($list_items->items) {
            $this->ok($list_items);
        } else {
            $this->ok($list_items, 20000, '列表没有更多消息');
        }
    }


    /**
     * 用户提现列表
     */
    public function withdrawlistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $withdraw   = new Withdraw();
        $list       = $withdraw->getWithdrawlist($this->params);
        $paginator  = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );
        $list_items = $paginator->getPaginate();
        $this->ok($list_items);
    }

    /**
     * 修改会员标签
     */
    public function userlabelAction()
    {
        if (!isset($this->params['id']) && empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $member = new Member();
        $info   = $member->find_by_id($this->params['id']);
        if (empty($info)) {
            $this->fail(-1, '该用户不存在');
        }
        $info['user_label'] = $this->params['userlabel'];
        $result             = $member->save_member($info);
        if ($result) {
            $this->ok([]);
        } else {
            $this->fail(-1, '修改标签失败');
        }
    }


    /**
     * 用户提现详情
     */
    public function withdrawdetailAction()
    {
        if (!isset($this->params['id']) && empty($this->params['id'])) {
            $this->fail(-1, '提现id不能为空');
        }
        $withdraw      = new Withdraw();
        $withdraw_info = $withdraw->find_by_id($this->params['id']);
        if (empty($withdraw_info)) $this->fail(-1, '没有找到提现记录');
        $member      = new Member();
        $member_info = $member->find_by_id($withdraw_info['user_id']);
        if (empty($member_info)) {
            $this->fail(-1, '没有找到用户信息');
        }
        $withdraw_info['phone']          = $member_info['phone'];
        $withdraw_info['nickname']       = $member_info['nickname'];
        $withdraw_info['wx_account']     = $member_info['weixin_no'];
        $withdraw_info['alipay_account'] = $member_info['alipay_account'];

        if ($withdraw_info['status'] == 1) $withdraw_info['status_name'] = '待审核';
        if ($withdraw_info['status'] == 2) $withdraw_info['status_name'] = '已通过';
        if ($withdraw_info['status'] == 3) $withdraw_info['status_name'] = '已拒绝';
        if ($withdraw_info['type'] == 1) $withdraw_info['type_name'] = '支付宝';
        if ($withdraw_info['type'] == 2) $withdraw_info['type_name'] = '微信';
        if ($withdraw_info['is_payed'] == 0) $withdraw_info['is_payed_name'] = '没有到账';
        if ($withdraw_info['is_payed'] == 1) $withdraw_info['is_payed_name'] = '已到账';
        if ($withdraw_info['is_payed'] == -1) $withdraw_info['is_payed_name'] = '失败';


        $this->ok($withdraw_info);
    }


    public function withdrawcheckAction()
    {
        if (!isset($this->params['id']) && empty($this->params['id'])) {
            $this->fail(-1, '提现id不能为空');
        }
        $withdraw      = new Withdraw();
        $withdraw_info = $withdraw->find_by_id($this->params['id']);
        if (!isset($this->params['status']) || empty($this->params['status'])) {
            $this->fail(-1, '请选择提现结果');
        }
        if ($this->params['status'] == 3) {
            if (!isset($this->params['tips']) || empty($this->params['tips'])) {
                $this->fail(-1, '不通过的时候，请填写原因');
            }
        }
        $withdraw_info['status']     = $this->params['status'];
        $withdraw_info['tips']       = $this->params['tips'];
        $withdraw_info['check_time'] = date('Y-m-d H:i:s', time());
        $result                      = $withdraw->save_withdraw($withdraw_info);

        $message = new Messages();
        switch ($this->params['status']) {
            case 2:
                $tips  = "您提现的余额{$withdraw_info['money']}元，后台已经审核通过了，系统将在24小时内完成转账。";
                $title = "余额提现后台审核结果";
                break;
            case 3:
                $tips  = "您提现的余额{$withdraw_info['money']}元，后台已经审核没有通过，原因:{$withdraw_info['tips']}。";
                $title = "余额提现后台审核结果";
                break;
            default:
                $tips  = "该笔{$withdraw_info['money']}元提现审核结果有问题，我们将做进一步处理";
                $title = "余额提现后台审核结果";
                break;
        }
        $message->save_params($withdraw_info['user_id'], $tips, $title);

        if ($result) {
            if ($this->params['push'] == 1) {
                $alias  = [$withdraw_info['user_id']];
                $title  = '您有新的审核通知';
                $detail = $this->params['status'] == 2 ? "您申请的{$withdraw_info['money']}元提现审核通过了，打款将在两个工作日完成" : "您申请的{$withdraw_info['money']}元体现审核没有通过，原因是：【{$this->params['tips']}】,请快速更正，重新提交申请。";
                $route  = [
                    'type'   => 1,
                    'path'   => 'AwakeMsg',
                    'title'  => '路由标题',
                    'url'    => '',
                    'data'   => '',
                    'notice' => null,
                ];
                $this->jpush->pushmsg_all($alias, $title, $detail, $route);
            }
            $this->ok([]);
        } else {
            $this->fail(-1, '审核失败');
        }
    }


    public function walletdetailAction()
    {
        $Withdraw        = new Withdraw();
        $UserMonthIncome = new UserMonthIncome();
        $Wallets         = new Wallets();
        $info            = $Withdraw->find_by_id($this->params['id']);
        $data            = [];
        $data['income']  = $UserMonthIncome->get_all_income($info['user_id']);
        $data['wallets'] = $Wallets->findbyUserMoney($info['user_id']);
        if ($data['wallets'] < 0) {
            $data['is_can_withdraw']  = 0;
            $data['can_can_withdraw'] = 0;
        } else {
            if (round($data['income'] - $data['wallets'], 2) >= $info['money']) {
                $data['is_can_withdraw']  = 1;
                $data['can_can_withdraw'] = $data['income'] - $data['wallets'];
            } else {
                $data['is_can_withdraw']  = 0;
                $data['can_can_withdraw'] = $data['income'] - $data['wallets'];
            }
            $this->ok($data);
        }
        var_dump($data);
        var_dump($info);
        echo 123;
        die;
    }

    public function privilegelistAction()
    {
        $FOperatorDb = new Operator();
        $f_operator = $FOperatorDb->find()->toarray();
        $this->ok($f_operator);
    }

    public function privilegeeditAction()
    {
        if (!isset($this->params['title']) || empty($this->params['title'])) {
            $this->fail(-1, '缺少参数title');
        }
        if (!isset($this->params['short_title']) || empty($this->params['short_title'])) {
            $this->fail(-1, '缺少参数短标题');
        }
        if (!isset($this->params['icon']) || empty($this->params['icon'])) {
            $this->params['icon']="";
        }
        $id     = isset($this->params['id']) ? $this->params['id'] : 0;
        $sort   = isset($this->params['sort']) ? $this->params['sort'] : 0;
        $equity = new Operator();

        $temp['title']    = $this->params['title'];
        $temp['short_title']      = $this->params['short_title'];
        $temp['icon']     = $this->params['icon'];
        $temp['sort']     = $sort;
        if ($id > 0) {
            $info = $equity->findFirst($id)->update($temp);
        } else {
            $info = $equity->save($temp);
        }
        if ($info) {
            $this->ok('操作成功!');
        } else {
            $this->fail(-1, $equity->getMessage());
        }
    }

    public function privilegedelAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '缺少参数id');
        }
        $equity = new Operator();
        $res    = $equity->findFirst($this->params['id'])->delete();
        if ($res) {
            $this->ok('操作成功!');
        }
        $this->fail(-1, $equity->getMessage());
    }


    /**
     * 会员订单
     */
    public function oclistAction()
    {
        $data   = [];
        $params = $this->params;
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        $data['page'] = $page;
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $data['keywords']  = $this->params['keywords'];
        $data['page_size'] = $pageSize;
        if (isset($params['order_status']) && !empty($params['order_status'])) {
            $data['order_status'] = $params['order_status'];
        }
        if (isset($params['tk_create_time']) && !empty($params['tk_create_time'])) {
            $data['tk_create_time'] = $params['tk_create_time'];
        }
        if (isset($params['site']) && !empty($params['site'])) {
            $data['site'] = $params['site'];
        }
        $model  = new Orders();
        $result = $model->getOrderList_list($data);
        $this->ok($result);
    }

    //商品转链接
    public function goods_turnAction()
    {
        if (!isset($this->params['goods_id']) || empty($this->params['goods_id'])) {
            $this->fail(-1, '商品id不能为空');
        }
        $data = '';
        switch ($this->params['site']) {
            case 'haodanku':
                $data = "https://detail.tmall.com/item.htm?id={$this->params['goods_id']}";
                break;
            case 'jd':
                $data = "https://item.jd.com/{$this->params['goods_id']}.html";
                break;
            case 'vph':
                $data = "https://m.vip.com/product-1710615119-{$this->params['goods_id']}.html";
                break;
            case 'koubei':
                $data = "https://detail.tmall.com/item.htm?id={$this->params['goods_id']}";
                break;
            case 'ele':
                $data = "https://detail.tmall.com/item.htm?id={$this->params['goods_id']}";
                break;
            case 'pdd':
                $res = $this->pdd_turn($this->params['goods_id'], '11199758_154538644');
                if (isset($res['status']) && $res['status'] === true) {
                    $data = $res['msg']['url'];
                }
                break;
            default:
                $this->fail(-1, '该商品已下架');
        }

        $this->ok($data);


        die();
        $params = $this->params;
        $user   = new User();
        if (!isset($params['site']) || empty($params['site'])) {

            $params['site'] = 'haodanku';
            //    $this->fail(-1,'站点不能为空');
        } else {
            if ($this->params['site'] != 'pdd' && $this->params['site'] != 'jd' && $this->params['site'] != 'haodanku' && $this->params['site'] != 'vph') {
                $this->fail(-1, '暂无详情!');
            }
        }
        if (!isset($params['goods_id']) || empty($params['goods_id'])) {
            $this->fail(-1, '商品id不能为空');
        }

        $redis_key = "goods_turn_{$params['site']}_{$params['goods_id']}_2591618978";
        $res       = $this->redis->get($redis_key);
        $res       = '';
        $url       = '';
        if (!$res) {
            switch ($params['site']) {
                case 'haodanku':
                    $res = Common::taobao_turn(2591618978, $params['goods_id']);      //商品转链
                    if (isset($res['status']) && $res['status'] === true) {
                        $url = $res['msg'];
                    }
                    break;
                case 'jd':
                    if (!isset($params['couponurl']) && empty($params['couponurl'])) {
                        $params['couponurl'] = '';
                    }
                    //$res = $this->jd->createturn($this->user_info['id'], $params['goods_id'], $params['couponurl']);
                    $res = $this->get_goods_link(2591618978, $params['goods_id'], $params['couponurl']);
                    if (isset($res['status']) && $res['status'] === true) {
                        $url = $res['short_url'];
                    }
                    break;

                case 'pdd':

                    $res = $this->pdd_turn($params['goods_id'], '11199758_154538644');
                    if (isset($res['status']) && $res['status'] === true) {
                        $url = $res['msg']['url'];
                    }
                    break;
                case 'vph':
                    $res = $this->vph->channel_createturn(1000000, $params['goods_id']);
                    if (isset($res['status']) && $res['status'] === true) {
                        $url = $res['msg']['url'];
                    }
                    break;
            }
            $this->redis->set($redis_key, $res);
        }
        $this->ok($url);
    }

    /**
     * @func获取拼多多的转链
     */
    public function pdd_turn($goods_id, $pid)
    {
        $xcx_params = [
            'goods_id_list'      => "[$goods_id]",
            'generate_short_url' => "true",
            'p_id'               => $pid,
            'generate_we_app'    => 'true',
            'type'               => 'pdd.ddk.goods.promotion.url.generate'//config('api.pin_duo_duo.product.promotion_url'),
        ];
        $app_params = [
            'goods_id_list'      => "[$goods_id]",
            'generate_short_url' => "true",
            'p_id'               => $pid,
            //'generate_we_app'=>'true',
            'type'               => 'pdd.ddk.goods.promotion.url.generate'//config('api.pin_duo_duo.product.promotion_url'),
        ];


        $params                    = array_merge($xcx_params, [
            'timestamp' => time(),
            'data_type' => 'JSON',
            'client_id' => '296d7ed93e4d4eb99f0b1a2c85537cf0',
        ]);
        $pdd_secret                = '46a0d7a33390ba61bbcb961dcb6d140bea24c170';
        $params                    = array_merge($params, ['sign' => (new Common())->sign($params, $pdd_secret)]);
        $pdd_params['form_params'] = $params;
        $url                       = 'http://gw-api.pinduoduo.com/api/router';
        $response                  = self::request_post($url, http_build_query($params));
        if (isset($response['error_response'])) {
            return ['status' => false, 'msg' => $response['error_response']['error_msg']];
        } else {
            $data = $response['goods_promotion_url_generate_response']['goods_promotion_url_list'][0];
            //注释2.0的
//            $result = (new Common())->promotion($goods_id,$pid,$data);
//            return ['status'=>true,'short_url'=>$data['short_url'],'msg'=>$result['url']];

            return ['status' => true, 'msg' => $data];//拼多多的所有链接
        }
    }

    public function request_post($request_url, $request_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data);
        $res = curl_exec($ch);
//        var_dump($res);exit;
        curl_close($ch);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 京推推转链
     */
    public function get_goods_link($positionid, $gid, $coupon_url)
    {
        $url                = 'http://japi.jingtuitui.com/api/get_goods_link';
        $data['appid']      = 2009011826041484;
        $data['appkey']     = '6450edcc6d415c45fb0bf62c2cfb2b5e';
        $data['unionid']    = 1003005478;
        $data['positionid'] = $positionid;
        $data['gid']        = $gid;
        $data['coupon_url'] = $coupon_url;
        $result             = Common::request_post($url, $data);
        if ($result['return'] == 0) {
            return ['status' => true, 'msg' => $result['result']['link'], 'short_url' => $result['result']['link']];
        } else {
            return ['status' => false, 'msg' => $result['result']];
        }
    }

    //我的直推粉丝
    public function my_direct_fansAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $this->params['limit'] = 5;
        }

        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '用户id不能为空');
        }

        if (!isset($this->params['type']) || empty($this->params['type'])) {
            $this->fail(-1, 'type不能为空');
        }
        $user               = new User();
        $get_list           = $user->my_direct_fans_sql($this->params);
        $order_commition_DB = new OrderCommissions();
        $walletDb           = new Wallets();
        $withdrawDb         = new Withdraw();
        foreach ($get_list as $key => $value) {
            $self_money                    = $order_commition_DB->self_order_commition_sum($value['id']);
            $get_list[$key]['self_amount'] = Common::number_randtwo($self_money);
            $user_wallet                   = $walletDb->findbyUserId($value['id']);
            $user_wallet_amount            = $user_wallet ? Common::number_randtwo($user_wallet->amount) : '0.00';
            $get_list[$key]['amount']      = $user_wallet_amount;
            $user_withdraw                 = $withdrawDb->user_money_totallist($value['id']);
            $get_list[$key]['all_amount']  = Common::number_randtwo($user_withdraw + $user_wallet_amount);
            $get_list[$key]['yugu_money']  = Common::number_randtwo($value['yugu_money']);
        }
        $total           = $user->my_direct_fans($this->params, 'count');
        $result['items'] = $get_list;
        $result['total'] = $total;
        $this->ok($result);
    }


    /**
     * 我的佣金明细
     */
    public function get_my_ordercommitionAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $this->params['limit'] = 5;
        }
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '用户id不能为空');
        }
        if (!isset($this->params['type']) || empty($this->params['type'])) {
            $this->params['type'] = 'all';
        }
        $order_commition_DB = new OrderCommissions();

        $get_list = $order_commition_DB->get_my_order_commition($this->params);
        $userDb   = new User();
        $ordersDb = new Orders();
        foreach ($get_list as $key => $value) {
            $user = $userDb->findFirstById($value['buyer_id']);
            if ($user) {
                $nickname = $user->nickname ? $user->nickname : $user->phone;
            } else {
                $nickname = '';
            }
            $get_list[$key]['nickname']  = $nickname;
            $orders                      = $ordersDb->findFirstByOrderId($value['order_id']);
            $get_list[$key]['price']     = $orders ? $orders->pay_money : '0.00';
            $get_list[$key]['all_money'] = CommonAd::number_randtwo($value['money'] + $value['money_plus']);
        }
        $total           = $order_commition_DB->get_my_order_commition($this->params, 'count');
        $result['items'] = $get_list;
        $result['total'] = $total;
        $this->ok($result);
    }


    /**
     * 我的佣金明细
     */
    public function get_selfmy_ordercommitionAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $this->params['limit'] = 5;
        }
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '用户id不能为空');
        }
        $order_commition_DB = new OrderCommissions();

        $get_list = $order_commition_DB->get_selfmy_order_commition($this->params);
        $userDb   = new User();
        $ordersDb = new Orders();
        foreach ($get_list as $key => $value) {
            $user = $userDb->findFirstById($value['buyer_id']);
            if ($user) {
                $nickname = $user->nickname ? $user->nickname : $user->phone;
            } else {
                $nickname = '';
            }
            $get_list[$key]['nickname']  = $nickname;
            $orders                      = $ordersDb->findFirstByOrderId($value['order_id']);
            $get_list[$key]['price']     = $orders ? $orders->price : '0.00';
            $get_list[$key]['all_money'] = Common::number_randtwo($value['money'] + $value['money_plus']);
        }
        $total           = $order_commition_DB->get_selfmy_order_commition($this->params, 'count');
        $result['items'] = $get_list;
        $result['total'] = $total;
        $this->ok($result);
    }

    public function getBalanceDetailAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '不存在!');
        }
        $page                = isset($this->params['page']) ? $this->params['page'] : 1;
        $size                = 10;
        $f_withdrawals       = new Withdraw();
        $where['conditions'] = "user_id = {$this->params['user_id']}";
        $data                = $f_withdrawals->find($where)->toarray();
        $result              = [];
        if (!empty($data)) {
            foreach ($data as $val) {
                $temp['user_id']         = $val['user_id'];
                $userDb                  = new User();
                $userWhere['conditions'] = "id = {$val['user_id']}";
                $userWhere['columns']    = "nickname,phone";
                $info                    = $userDb->findFirst($userWhere);
                $temp['nickname']        = $info->nickname ? $info->nickname : $info->phone;
                $temp['money']           = $val['money'];
                $temp['explain']         = '提现金额';
                $temp['time']            = $val['created_at'];
                $result[]                = $temp;
            }
        }
        $user_month_income = new UserMonthIncome();
        $newData           = $user_month_income->find($where)->toarray();
        if (!empty($newData)) {
            foreach ($newData as $vals) {
                $temp['user_id']         = $vals['user_id'];
                $userDb                  = new User();
                $userWhere['conditions'] = "id = {$vals['user_id']}";
                $userWhere['columns']    = "nickname,phone";
                $info                    = $userDb->findFirst($userWhere);
                $temp['nickname']        = $info->nickname ? $info->nickname : $info->phone;
                $temp['money']           = $vals['commission'] + $vals['market'] + $vals['area'] + $vals['ad'] + $vals['red'] + $vals['new_people'] + $vals['new_area_people'];
                $temp['explain']         = '月收入';
                $temp['time']            = date('Y-m-d H:i:s', strtotime($vals['month']));
                $result[]                = $temp;
            }
        }
        $list['total'] = count($result);

        if (!empty($result)) {
            foreach ($result as $key => $row) {
                $num1[$key] = $row ['time'];
            }

            array_multisort($num1, SORT_DESC, $result);
            $page   = $page == 1 ? 0 : ($page - 1) * $size;
            $result = array_slice($result, $page, $size);
        }
        $list['list'] = $result;
        $this->ok($list);
    }

    public function estimatedRevenueAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '不存在!');
        }

        $commission = new OrderCommissions();
        $thisM      = ToolsController::timeChange(8);
        $lastM      = ToolsController::timeChange(9);
        $thisD      = ToolsController::timeChange(1);
        $lastD      = ToolsController::timeChange(2);
        //本月结算
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $thisM);
        $result['this_m_js_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['this_m_js_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['this_m_js_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['this_m_js_count']  = $result['this_m_js_taobao'] + $result['this_m_js_pdd'] + $result['this_m_js_jd'];
        //上月结算
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $lastM);
        $result['last_m_js_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['last_m_js_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['last_m_js_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['last_m_js_count']  = $result['last_m_js_taobao'] + $result['last_m_js_pdd'] + $result['last_m_js_jd'];

        //本月付款预估
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $thisM, 1);
        $result['this_m_fk_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['this_m_fk_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['this_m_fk_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['this_m_fk_count']  = $result['this_m_fk_taobao'] + $result['this_m_fk_pdd'] + $result['this_m_fk_jd'];
        //上月付款预估
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $lastM, 1);
        $result['last_m_fk_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['last_m_fk_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['last_m_fk_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['last_m_fk_count']  = $result['last_m_fk_taobao'] + $result['last_m_fk_pdd'] + $result['last_m_fk_jd'];
        //今日付款笔算
        $data                       = $commission->getFkCount($this->params['user_id'], $thisD);
        $result['this_d_bs_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['this_d_bs_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['this_d_bs_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['this_d_bs_count']  = $result['this_d_bs_taobao'] + $result['this_d_bs_pdd'] + $result['this_d_bs_jd'];
        //今日预计佣金
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $thisD, 1);
        $result['this_d_yj_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['this_d_yj_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['this_d_yj_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['this_d_yj_count']  = $result['this_d_yj_taobao'] + $result['this_d_yj_pdd'] + $result['this_d_yj_jd'];
        //昨日付款笔数
        $data                       = $commission->getFkCount($this->params['user_id'], $lastD);
        $result['last_d_bs_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['last_d_bs_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['last_d_bs_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['last_d_bs_count']  = $result['last_d_bs_taobao'] + $result['last_d_bs_pdd'] + $result['last_d_bs_jd'];
        //昨日预计佣金
        $data                       = $commission->getUserSettlementCount($this->params['user_id'], $lastD, 1);
        $result['last_d_yj_taobao'] = isset($data['haodanku']) ? $data['haodanku'] : 0;
        $result['last_d_yj_pdd']    = isset($data['pdd']) ? $data['pdd'] : 0;
        $result['last_d_yj_jd']     = isset($data['jd']) ? $data['jd'] : 0;
        $result['last_d_yj_count']  = $result['last_d_yj_taobao'] + $result['last_d_yj_pdd'] + $result['last_d_yj_jd'];

        $this->ok($result);
    }


    //修改用户信息
    public function update_memberAction()
    {
        $userDb = new Member();
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '请传入用户id');
        }
        $user_find_one = $userDb->findFirstById($this->params['id']);
        if (!$user_find_one) {
            $this->fail(-1, '没有找到记录行');
        }
        if (!isset($this->params['invite_code']) || empty($this->params['invite_code'])) {
            $this->fail(-1, '邀请码不能为空');
        } else {
            if ($this->params['invite_code'] != $user_find_one->invite_code) {
                $is_invite_code = $userDb->find_by_inviteCode($this->params['invite_code']);
                if ($is_invite_code) {
                    $this->fail(-1, '邀请码已经被占用');
                }
                $user_find_one->invite_code = $this->params['invite_code'];
            }
        }
        if (isset($this->params['password']) && !empty($this->params['password'])) {
            $user_find_one->password = md5(md5($this->params['password']));
        }
        $user_find_one->alipay_account = $this->params['alipay_account'];
        $user_find_one->is_disable     = $this->params['is_disable'];
        $user_find_one->real_name      = $this->params['real_name'];
        $user_find_one->nickname       = $this->params['nickname'];
        if ($user_find_one->save()) {
            $invite_codeDb   = new InviteCodes();
            $invite_find_one = $invite_codeDb->findFirstById($this->params['invite_code']);
            if ($invite_find_one) {
                $invite_find_one->used       = 1;
                $invite_find_one->created_at = date('Y-m-d H:i:s');
                $invite_find_one->updated_at = date('Y-m-d H:i:s');
                $invite_find_one->save();
            }
            $this->ok([]);
        } else {
            $this->fail(-1, '修改失败');
        }

    }


    /**
     * 积分明细列表
     */
    public function integralListAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '请传入用户user_id');
        }
        $f_user_gold_coin_log = new UserGoldCoinLog();
        $list                 = $f_user_gold_coin_log->page_list($this->params);
        $this->ok($list);
    }

    /**
     * 金币明细列表
     */
    public function goldListAction()
    {
        $f_user_gold_coin_new_log = new FUserGoldCoinNewLog();
        $list                     = $f_user_gold_coin_new_log->page_list($this->params);
        $this->ok($list);
    }

    /**
     * 金币统计
     */
    public function getGoldCountAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '请传入用户user_id');
        }
        $wall                     = new Wallets();
        $wallInfo                 = $wall->findbyUserId($this->params['user_id']);
        $f_user_gold_coin_new_log = new FUserGoldCoinNewLog();
        $result['add_count']      = $f_user_gold_coin_new_log->sumNum(1, $this->params['user_id']);
        $result['out_count']      = $f_user_gold_coin_new_log->sumNum(2, $this->params['user_id']);
        $result['count']          = Common::number_randtwo($wallInfo->gold_money);
        $result['empty_count']    = Common::number_randtwo($f_user_gold_coin_new_log->sumNumEmpty($this->params['user_id']));

        $f_user_gold_coin_frozen = new FUserGoldCoinFrozen();
        $where['conditions']     = "user_id = {$this->params['user_id']} and status = 0";
        $where['columns']        = "sum(num) as num";
        $frozen                  = $f_user_gold_coin_frozen->findFirst($where);
        $result['frozen_count']  = $frozen->num ? $frozen->num : 0;
        $this->ok($result);
    }

    /**
     * 积分统计
     */
    public function getIntegralCountAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '请传入用户user_id');
        }
        $f_user_gold_coin_log = new UserGoldCoinLog();
        $result['add_count']  = $f_user_gold_coin_log->sumNum(1, $this->params['user_id']);
        $result['out_count']  = $f_user_gold_coin_log->sumNum(2, $this->params['user_id']);
        $result['count']      = Common::number_randtwo($result['add_count'] - $result['out_count'], 2);
        $this->ok($result);
    }

    /**
     * 批量审核
     */
    public function withdrawallAction()
    {
        if (!isset($this->params['w_ids']) && empty($this->params['w_ids'])) {
            $this->fail(-1, '提现w_ids不能为空');
        }
        $withdraw      = new Withdraw();
        $withdraw_info = $withdraw->find_by_id_list($this->params['w_ids']);
        if (!empty($withdraw_info->toarray())) {
            $UserMonthIncome = new UserMonthIncome();
            $Wallets         = new Wallets();
            $this->dbMaster->begin();
            foreach ($withdraw_info as $value) {
                $info = $value->toarray();

                $data           = [];
                $data['income'] = $UserMonthIncome->get_all_income($info['user_id']);

                $data['wallets'] = $Wallets->findbyUserMoney($info['user_id']);
                if ($data['wallets'] < 0) {
                    $status = 3;
                    $tips   = "您提现的余额{$value['money']}元，后台已经审核没有通过，原因:用户核账金额不对。";
                    $title  = "余额提现后台审核结果";
                } else {

                    if (round($data['income'] - $data['wallets'], 2) >= $info['money']) {
                        $status = 2;

                        $tips  = "您提现的余额{$info['money']}元，后台已经审核通过了，系统将在24小时内完成转账。";
                        $title = "余额提现后台审核结果";
                    } else {
                        $status = 3;
                        $tips   = "您提现的余额{$info['money']}元，后台已经审核没有通过，原因:用户核账金额不对。";
                        $title  = "余额提现后台审核结果";
                    }
                }

                $value->status     = $status;
                $value->tips       = $tips;
                $value->check_time = date('Y-m-d H:i:s', time());
                if (!$value->save()) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '审核失败1');
                }

                $message = new Messages();
                $msg     = $message->save_params($info['user_id'], $tips, $title);
                if (!$msg) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '审核失败2');
                }
                $alias  = [$info['user_id']];
                $title  = '您有新的审核通知';
                $detail = $tips;
                $route  = [
                    'type'   => 1,
                    'path'   => 'AwakeMsg',
                    'title'  => '路由标题',
                    'url'    => '',
                    'data'   => '',
                    'notice' => null,
                ];
                $this->jpush->pushmsg_all($alias, $title, $detail, $route);
            }
            $this->dbMaster->commit();
            $this->ok([]);
        } else {
            $this->fail(-1, '没有找到审核数据');
        }

    }


    /**
     *添加修改备注信息
     */
    public function updateremarkAction()
    {
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '用户id不能为空');
        }
        if (!isset($this->params['remark']) || empty($this->params['remark'])) {
            $this->fail(-1, '备注信息不能为空');
        }
        $member      = new Member();
        $member_find = $member->findFirstById($this->params['user_id']);
        if (!$member_find) {
            $this->fail(-1, '没有找到用户');
        }
        $member_find->remark = $this->params['remark'];
        if ($member_find->save()) {
            $this->ok([]);
        }
        $this->fail(-1, '操作失败');
    }


    //新增 数据汇总1.总佣金  2.今日 3.昨日 4.7日 5.30日  预估汇总   点击直邀和间邀 间邀以后 的汇总数据不一样
    public function member_commitionAction()
    {
        if (!isset($this->params['type']) || empty($this->params['type'])) {
            $this->params['type'] = 1;
        }
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '用户id不能为空');
        }

        $userDb          = new User();
        $ordercommission = new OrderCommissions();
        switch ($this->params['type']) {
            case 1: //直邀
                $ids    = $userDb->referer_ids($this->params['user_id']);
                $result = $ordercommission->order_commision_money($ids);
                break;
            case 2: //间接
                $ids    = $userDb->indirect_ids($this->params['user_id']);
                $result = $ordercommission->order_commision_money($ids);
                break;
            case 3: //间接以后
                $ids    = $userDb->indirect_indirect_ids($this->params['user_id']);
                $result = $ordercommission->order_commision_money($ids);
                break;
            default:
                $this->fail(-1, '参数错误');
                break;
        }
        $this->ok($result);
    }


    public function add_userAction()
    {
        $member = new Member();
        if (!isset($this->params['phone']) || empty($this->params['phone'])) {
            $this->fail(-1, '电话号码不能为空');
        } else {
            if (!preg_match("/^1[3456789]{1}\d{9}$/", $this->params['phone'])) {
                $this->fail(-1, '手机号码错误');
            }
            $is_phone = $member->find_by_phone($this->params['phone']);
            if ($is_phone) {
                $this->fail(-1, '电话号码已经存在');
            }
        }
        if (!isset($this->params['password']) || empty($this->params['password'])) {
            $this->fail(-1, '密码不能为空');
        } else {
            if (strlen($this->params['password']) < 6) {
                $this->fail(-1, '密码长度必须大于6');
            }
        }
        $member->phone      = $this->params['phone'];
        $member->nickname   = substr_replace($this->params['phone'], '****', 3, 4);
        $member->level_id   = 1;
        $member->password   = md5($this->params['password']);
        $member->referer_id = 1;
        $member->path       = '';
        $member->created_at = date('Y-m-d H:i:s');
        $member->updated_at = date('Y-m-d H:i:s');
        $member->remark     = '后台添加用户';
        if ($member->save()) {
            $this->ok([]);
        }
        $this->fail([]);
    }


    // 删除会员
    public function delete_memberAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '会员id不能为空');
        }
        $userDb   = new User();
        $find_one = $userDb->findFirstById($this->params['id']);
        if (!$find_one) {
            $this->fail(-1, '没有找到记录行');
        }
        $orderDb     = new Orders();
        $count_order = $orderDb->count(array(
            'conditions' => "user_id={$this->params['id']}",
            'columns'    => 'id',
            'limit'      => 1,
        ));
        if ($count_order) {
            $this->fail(-1, '不能删除，该好友已经有订单');
        }
        $count_order_commissionDb  = new OrderCommissions();
        $count_order_coummissionDb = $count_order_commissionDb->count(array(
            'conditions' => "user_id={$this->params['id']}",
            'columns'    => 'id',
            'limit'      => 1,
        ));
        if ($count_order_coummissionDb) {
            $this->fail(-1, '不能删除，该好友已经有分佣');
        }
        $count_referer_count = $userDb->count(array(
            'conditions' => "referer_id={$this->params['id']}",
            'columns'    => 'id',
            'limit'      => 1,
        ));
        if ($count_referer_count) {
            $this->fail(-1, '不能删除，该好友已经有下级会员');
        }

        if ($find_one->delete()) {
            $this->ok([]);
        }
        $this->fail(-1, '删除失败');
    }

    /**
     * 清除金币
     */
    public function emptyGoldAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '缺少ID');
        }
        if (!isset($this->params['type']) || empty($this->params['type'])) {
            $this->fail(-1, '缺少type');
        }

        $this->dbMaster->begin();
        if ($this->params['type'] == 1) {
            $wall     = new Wallets();
            $wallInfo = $wall->findbyUserId($this->params['id']);
            if ($wallInfo->gold_money == 0) {
                $this->fail(-1, '该用户没有金币!');
            }

            $f_user_gold_coin_new_log             = new FUserGoldCoinNewLog();
            $f_user_gold_coin_new_log->user_id    = $this->params['id'];
            $f_user_gold_coin_new_log->oil_num    = $wallInfo->gold_money;
            $f_user_gold_coin_new_log->this_num   = 0;
            $f_user_gold_coin_new_log->num        = $wallInfo->gold_money;
            $f_user_gold_coin_new_log->type       = 7;
            $f_user_gold_coin_new_log->status     = 2;
            $f_user_gold_coin_new_log->remarks    = '清空金币';
            $f_user_gold_coin_new_log->created_at = date('Y-m-d H:i:s');
            if (!$f_user_gold_coin_new_log->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '清除日志保存失败!');
            }

            $wallInfo->gold_money = 0;
            if (!$wallInfo->save()) {
                $this->fail(-1, '钱包保存失败!');
            }
        } else {
            $f_user_gold_coin_frozen = new FUserGoldCoinFrozen();
            $where['conditions']     = "user_id = {$this->params['id']} and status = 0";
            $frozenData              = $f_user_gold_coin_frozen->find($where);
            if (!empty($frozenData->toarray())) {
                $gold = 0;
                foreach ($frozenData as $val) {
                    $gold         += $val->num;
                    $val->status  = 2;
                    $val->remarks = '清空金币';
                    if (!$val->save()) {
                        $this->dbMaster->rollback();
                        $this->fail(-1, '冻结清除失败!');
                    }
                }

                $f_user_gold_coin_new_log             = new FUserGoldCoinNewLog();
                $f_user_gold_coin_new_log->user_id    = $this->params['id'];
                $f_user_gold_coin_new_log->oil_num    = 0;
                $f_user_gold_coin_new_log->this_num   = 0;
                $f_user_gold_coin_new_log->num        = $gold;
                $f_user_gold_coin_new_log->type       = 8;
                $f_user_gold_coin_new_log->status     = 2;
                $f_user_gold_coin_new_log->remarks    = '清空冻结金币';
                $f_user_gold_coin_new_log->created_at = date('Y-m-d H:i:s');
                if (!$f_user_gold_coin_new_log->save()) {
                    $this->dbMaster->rollback();
                    $this->fail(-1, '清除日志保存失败!');
                }
            } else {
                $this->fail(-1, '该用户没有金币!');
            }
        }
        $this->dbMaster->commit();
        $this->ok();
    }


}
